package dai.samples.shiro.controller;

import dai.samples.shiro.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 进行登录的相关请求
 */
@RestController
public class LoginController {

    @RequestMapping("/login")
    public String login(User user) {
        // 添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        // 创建需要进行登录的认证主体
        AuthenticationToken usernamePasswordToken =
            new UsernamePasswordToken(user.getLoginName(), user.getPassword());
        try {
            // 进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return "账号或密码错误！";
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return "没有权限";
        }
        return "login success";
    }

    @RequestMapping("/logout")
    public String logout() {
        // 添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "logout success";
    }

}
